<template>
  <el-select
    v-bind="$attrs"
    collapse-tags
    v-model.lazy="selectValue"
    style="width: 100%"
    :filterMethod="filterMethod"
    @change="changeSelectValue"
    @visible-change="visibleChange"
  >
    <el-option
      v-for="(item, index) in optionsList"
      :key="index.key"
      :label="item.key.length > 8 ? item.key.substring(0, 8) + '...' : item.key"
      :value="item.value"
    />
  </el-select>
</template>

<script setup name="SelectMultiple">
import pinyin from 'js-pinyin'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  modelValue: {
    type: [Number, String],
  },
  value: {
    type: String,
    default: '',
  },
  keyField: {
    type: String,
    default: 'name',
  },
  valueField: {
    type: String,
    default: 'id',
  },
  clearType: {
    type: Boolean,
    default: true,
  },
  options: {
    type: Array,
    default: function () {
      return []
    },
  },
})
const selectValue = ref('')
const optionsList = ref([])
const copyOptions = ref([])
watch(
  () => props.value,
  (val) => {
    if (val) {
      if (proxy.$attrs.multiple) {
        //转整型
        let splitVal = proxy.$fn.splitArr(val).map((item) => item.toString())
        if (splitVal.length && splitVal[0] != 'true') {
          selectValue.value = splitVal
        }
      } else {
        selectValue.value = val
      }
    }
  }
)
watch(
  () => props.clearType,
  (val) => {
    selectValue.value = ''
  }
)
watch(
  () => props.options,
  (val) => {
    optionsList.value = proxy.$fn.deepClone(val)
    copyOptions.value = proxy.$fn.deepClone(val)
  },
  {
    deep: true,
    immediate: true,
  }
)
function visibleChange(val) {
  //下拉框出现/隐藏时触发
  if (!val) {
    optionsList.value = copyOptions.value
  }
}
function filterMethod(value) {
  // 自定义搜索方法
  if (value) {
    let result = []
    console.log(value)
    copyOptions.value.forEach((item) => {
      pinyin.setOptions({ checkPolyphone: false, charCase: 1 })
      const resultEng = pinyin.getCamelChars(item.key).toUpperCase()
      const matchResult =
        item.key.indexOf(value) !== -1 || resultEng.indexOf(value.toUpperCase()) !== -1
      // let matchResult = PinYinMatch.match(item.key, value)
      if (matchResult) {
        result.push(item)
      }
    })
    optionsList.value = result
  } else {
    optionsList.value = copyOptions.value
  }
}
function changeSelectValue(val) {
  if (proxy.$attrs.multiple) {
    emits('update:modelValue', val.toString())
    emits('select', val.toString())
  } else {
    emits('update:modelValue', val)
    emits('select', val)
  }
  emits('change', val)
}
</script>

<style scoped></style>
